<template>
  <div>
    <el-dialog v-loading="loading" :title="title" :visible.sync="open" width="800px" append-to-body :before-close="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-divider content-position="center">基础设置</el-divider>
          <el-col :span="12">

            <el-form-item label="文章来源" prop="source">
              <el-radio v-model="form.source" label="公众号">公众号</el-radio>
              <el-radio v-model="form.source" label="网页">网页</el-radio>
            </el-form-item>
            <el-form-item label="搜索名称" prop="search_name">
              <el-input v-model="form.search_name" placeholder="请输入搜索名称" />
            </el-form-item>

            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>

             <el-form-item label="发布标题">
              <el-input v-model="form.publish_title" placeholder="请输入发布标题" />
            </el-form-item>

            <el-form-item label="路径">
              <el-input v-model="form.path" disabled placeholder="请输入路径" />
            </el-form-item>

            <el-form-item label="新闻分类" prop="cate_id">
              <el-select v-model="form.cate_id" placeholder="请选择新闻分类" style="width:100%" @change="changeCate">
                <el-option
                  v-for="(item, index) in cate_list"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预留字段1">
              <el-input v-model="form._ext_field_1" placeholder="预留字段1" />
            </el-form-item>

            <!-- <el-button type="primary" @click="log">123123</el-button> -->
            <el-form-item label="封面图片">
              <el-upload
                class="upload-demo"
                :action="imageAction"
                :headers="{ 'Authorization': 'Bearer ' + authToken, }"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-upload="beforeUpload"
                :file-list="fileList"
                list-type="picture-card"
                :limit="1"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>

            <el-form-item label="是否推荐" prop="is_rec">
              <el-switch
                v-model="form.is_rec"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>

            <el-form-item label="是否推荐2" prop="is_rec2">
              <el-switch
                v-model="form.is_rec2"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>

            <el-form-item label="分数">
              <el-input-number :min="0" :max="1000" v-model="form.score" placeholder="请输入分数" />
            </el-form-item>

            <el-form-item label="标签">
              <el-select v-model="form.tags" multiple placeholder="请选择标签">
                <el-option v-for="item in tagsOptions" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-divider content-position="center">其他设置</el-divider>

          <el-form-item label="图文详情">
            <!-- <ckeditor v-model="editorData" :editor="editor" :config="editorConfig" /> -->
            <!-- <quill-editor v-model="editorData" /> -->

          </el-form-item>
          <vue-ueditor-wrap
            v-model="content"
            editor-id="editor"
            :config="editorConfig"
            :editor-dependencies="['ueditor.config.js','ueditor.all.js']"
            style="height:500px;"
          />
        </el-row>
        <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
          <el-col :span="24">
            <el-button type="primary" size="medium" @click="submitForm('form')">{{ title }}</el-button>
            <el-button size="medium" @click="close()">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { postGoods, editGoods, getCategory, editNews, addNews, getNewsDetail } from '@/api/externalGoods'
import { officialTagsList } from '@/api/basics'
import VueUeditorWrap from 'vue-ueditor-wrap'

export default {
  name: 'jsNewsAddEdit',
  components: {
    VueUeditorWrap
  },
  props: ['open', 'form', 'title', 'cate_list'],
  // props: {
  //   open: {
  //     type: Boolean
  //   },
  //   form: {
  //   },
  //   title: {
  //     type: String
  //   }
  // },
  data() {
    return {
      tagsOptions: [],
      loading: true,
      list: [{ id: 1, int_name: '', int_1: '' }],
      list2: [],
      total: 0,
      goods_img: [],
      queryParams: {
        page: 1,
        limit: 10
      },
      rules: {
        // is_rec: [
        //   { required: true, message: '请选择文章是否推荐', trigger: 'blur' }
        // ],
        // is_rec2: [
        //   { required: true, message: '请选择文章是否推荐2', trigger: 'blur' }
        // ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'blur' }
        ],
        // path: [
        //   { required: true, message: '请选择文章path', trigger: 'blur' }
        // ],
        source: [
          { required: true, message: '请选择文章来源', trigger: 'blur' }
        ],
        search_name: [
          { required: true, message: '请输入搜索名称', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        cover_url: [
          { required: true, message: '请上传封面图片', trigger: 'blur' }
        ]
      },
      fileList: [],
      authToken: this.$store.state.user.token,
      imageAction: '/imgapi/upload_file.php?tid=10918',
      radio: '1',
      content: '<p>请输入详情</p>',
      editorConfig: {
        // 编辑器后端服务接口，参考后端规范 https://open-doc.modstart.com/ueditor-plus/backend.html
        serverUrl: 'https://img.qekj.net/php/controller.php',
        // 配置 UEditorPlus 的静态资源根路径，可以是 CDN 的静态资源地址
        UEDITOR_HOME_URL: '/UEditor/',
        // UEDITOR_CORS_URL: '/static/UEditorPlus'
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        zIndex: 3000
      },
      options1: [],
      props: { checkStrictly: true, label: 'name', value: 'id' },
      category_ids: [],
      ifAdmin: false
    }
  },
  watch: {
    'open': function(newValue, oldValue) {
      if (newValue) {
        if (this.title === '编辑') {
          // 获取详情数据
          getNewsDetail(this.form.id).then(res => {
            if (res.code === 10000) {
              this.form = res.data
              this.content = this.form.content_html
              this.fileList = []
              if (this.form.cover_url) {
                this.fileList.push({ url: this.form.cover_url })
              }
            }
          })
        } else {
          this.fileList = []
          this.goods_img = []
          this.list = [{ id: 1, int_name: '', int_1: '' }]
          this.list2 = []
          this.content = '<p>请输入详情</p>'
          this.radio = '1'
        }
      }
    }
  },
  mounted() {
  },
  created() {
    this.getCategoryList()

    // 获取公众号标签 设置查询参数 page=1 limit=1000
    officialTagsList({ page: 1, limit: 1000 }).then(response => {
      this.tagsOptions = response.data
    })
  },
  methods: {
    changeCate(val) {
      let obj = {}
      obj = this.cate_list.find((item) => {
        return item.id === val
      })
      this.form.cate_name = obj.name
    },
    deepTraverse(arr) {
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          this.deepTraverse(arr[i])
        } else if (typeof arr[i] === 'object') {
          this.deepTraverse(Object.values(arr[i]))
          this.convertIdToNumber(arr[i])
        }
      }
    },
    convertIdToNumber(obj) {
      for (var key in obj) {
        if (typeof obj[key] === 'object') {
          this.convertIdToNumber(obj[key])
        } else if (key === 'cate_id' && typeof obj[key] === 'string') {
          obj[key] = parseInt(obj[key])
        }
      }
    },
    getCategoryList() {
      getCategory().then(response => {
        this.options1 = response.data
        this.deepTraverse(this.options1)
        // console.log(this.options1)
      })
    },
    log() {
      console.log(this.fileList)
    },
    delTable(val) {
      this.list2.forEach((item, index) => {
        if (item.id === val) {
          this.list2.splice(index, 1)
        }
      })
    },
    cartesianProduct(arrays) {
      return arrays.reduce(function(a, b) {
        var result = []
        a.forEach(function(x) {
          b.forEach(function(y) {
            result.push(x.concat([y]))
          })
        })
        return result
      }, [[]])
    },
    del(val) {
      this.list = this.list.filter(item => item.id !== val)
    },
    addList() {
      var id = this.list.length + 1
      this.list.forEach(item => {
        if (item.id === id) {
          id++
        }
      })
      this.list.push({ id, int_name: '', int_1: '' })
    },
    handleSuccess(response, file, fileList) {
      this.form.cover_url = response.http_url
      const list = {
        name: file.name,
        url: response.http_url
      }
      this.fileList = [list]
    },
    handleError(error, file, fileList) {
      // 上传失败的处理逻辑
      console.log('上传失败', error)
      this.$message({
        message: '上传失败',
        type: 'error'
      })
    },
    beforeUpload(file) {
      // 文件上传之前的处理逻辑
      // console.log('文件上传之前', file)
    },
    handleRemove(file, fileList) {
      // 删除文件的处理逻辑
      this.fileList = []
      this.form.cover_url = ''
    },
    close() {
      this.$emit('update:open', false)
    },
    getList() {

    },
    submitForm() {
      this.$refs['form'].validate((valid, errorFields) => {
        if (valid) {
          this.form.content_html = this.content
          if (this.title == '添加') {
            //添加 is_jiangsu_zone 1
            this.form.is_jiangsu_zone = 1
            addNews(this.form).then(res => {
              if (res.code == 10000) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.$emit('update:open', false)
                this.$emit('refresh')
              }
            })
          } else {
            editNews(this.form.id, this.form).then(res => {
              if (res.code == 10000) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.$emit('update:open', false)
                this.$emit('refresh')
              }
            })
          }
        } else {
          // 获取第一个错误信息
          const firstError = Object.values(errorFields)[0][0].message;
          this.$notify({
            title: '警告',
            message: firstError,
            type: 'warning',
            duration: 3000
          });
          return false
        }
      })
    }
  }
}
</script>

<style>
.upload-demo {
  display: inline-block;
  margin-bottom: 20px;
}

.el-upload-list--picture-card {
  width: 500px;
  display: flex !important;
  flex-wrap: wrap;
}
.el-input__inner {
  width: 100% !important;
}

</style>
